package com.yzh.wanandroid.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.LoadState
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.yzh.wanandroid.R
import com.yzh.wanandroid.databinding.ItemListBinding
import com.yzh.wanandroid.model.RefreshData
import com.yzh.wanandroid.network.retrofit.responsebean.ListData

class SquareAdapter :
    PagingDataAdapter<ListData, SquareAdapter.SquareViewHolder>(SQUARE_DIFF_CALLBACK) {


    var refreshData = RefreshData()

    init {
        this.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> refreshData.isfreshing = false
                is LoadState.Loading -> refreshData.isfreshing = true
                is LoadState.Error -> refreshData.isfreshing = false
                else -> refreshData.isfreshing = false
            }
        }
    }

    private lateinit var mOnClickListener: (View, String, String) -> Unit

    fun setOnClickListener(onClickListener: (View, String, String) -> Unit) {
        this.mOnClickListener = onClickListener
    }

    override fun onBindViewHolder(holder: SquareAdapter.SquareViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): SquareAdapter.SquareViewHolder {
        val squareBinding: ItemListBinding =
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.item_list,
                parent,
                false
            )
        return SquareViewHolder(squareBinding)
    }

    inner class SquareViewHolder(private val binding: ItemListBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(data: ListData?) {
            binding.run {
                model = data
                cardView.setOnClickListener { view ->
                    data?.let { mOnClickListener.invoke(view, it.link, it.title) }
                }
                executePendingBindings()
            }
        }
    }

    companion object {
        private val SQUARE_DIFF_CALLBACK: DiffUtil.ItemCallback<ListData> =
            object : DiffUtil.ItemCallback<ListData>() {
                override fun areItemsTheSame(
                    oldResult: ListData,
                    newResult: ListData
                ): Boolean {
                    return oldResult.id == newResult.id
                }

                @SuppressLint("DiffUtilEquals")
                override fun areContentsTheSame(
                    oldResult: ListData,
                    newResult: ListData
                ): Boolean {
                    return oldResult == newResult
                }
            }
    }

}